package com.yzt.loginmodule.widget;

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;

/**
 * <pre>
 *     author : TK
 *     time   : 2017/06/23
 *     desc   : 软键盘工具
 * </pre>
 */
public final class KeyBoardUtils {
    public static final String TAG = "KeyBoardUtils";
    public static final String HEIGHT = "height";
    public static final float DEFAULT_HEIGHT = 0.4f;

    private KeyBoardUtils() {
        throw new IllegalStateException();
    }

    /**
     * 显示软键盘
     *
     * @param view
     */
    public static void showKeyboard(@NonNull View view) {
        InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 隐藏软键盘
     *
     * @param view
     */
    public static void hideKeyboard(@NonNull View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 记录软键盘高度
     *
     * @param context
     * @param height
     */
    public static void saveKeyboardHeight(@NonNull Context context, int height) {
        context.getSharedPreferences(TAG, Context.MODE_PRIVATE).edit().putInt(HEIGHT, height).apply();
    }

    /**
     * 获取键盘高度
     *
     * @param context
     * @return
     */
    public static int getKeyboardHeight(@NonNull Context context) {
        int h = context.getSharedPreferences(TAG, Context.MODE_PRIVATE).getInt(HEIGHT, 0);
        if (0 >= h) {
            //默认的软键盘高度
            return (int) (context.getResources().getDisplayMetrics().heightPixels * DEFAULT_HEIGHT);
        }
        return h;
    }
}
